//
//  PEGainFullChartVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/11/2.
//

#import "RHEnergyStatisticsFullChartVC.h"
#import "DevParamsAlertController.h"
#import "DeviceChartFieldModel.h"
#import "RHWindowTipManage.h"
#import "DevChartModel.h"
#import "AppDelegate.h"
#import "WSDatePickerView.h"
#import "RHEnergyStatisticsChartView.h"
#import "DevChartTypeModel.h"

@interface RHEnergyStatisticsFullChartVC ()
@property (nonatomic ,strong) RHEnergyStatisticsChartView *chartView;

@property (nonatomic ,strong) DevChartModel *chartModel;

@property (nonatomic ,assign) RHPlantModel *plantModel;

@property (nonatomic ,assign) NSInteger toolType;

@end

@implementation RHEnergyStatisticsFullChartVC


- (instancetype)initWithModel:(DevChartModel *)chartModel plantModel:(RHPlantModel*)plantModel toolType:(NSInteger)toolType;
{
    self = [super init];
    if (self) {
        self.chartModel = chartModel;
        self.plantModel = plantModel;
        self.toolType = toolType;
        
    }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"Full Chart";
    self.isUnPopGes = YES;
    [self setupUI];
   
}



- (void)setupUI{
    _chartView = [[RHEnergyStatisticsChartView alloc] initWithFrame:CGRectMake(kSafe_top, 0,kUI_WINDOW_H - kSafe_top,kUI_WINDOW_W - kSafe_bottom) type:self.toolType isLandscape:YES];
    _chartView.canScale = YES;
    [self.bgView addSubview:_chartView];
    kWeakSelf;
    _chartView.fullChartBlock = ^{
        AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
           delegate.allowRotate = 0;
        if(@available(iOS 16.0, *)) {
            [weakSelf.navigationController setNeedsUpdateOfSupportedInterfaceOrientations];
            NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
            UIWindowScene *ws = (UIWindowScene *)array[0];
            UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [[UIWindowSceneGeometryPreferencesIOS alloc] init];
            geometryPreferences.interfaceOrientations = UIInterfaceOrientationMaskPortrait;
            [ws requestGeometryUpdateWithPreferences:geometryPreferences errorHandler:^(NSError * _Nonnull error) {
                 //业务代码
            }];
        }else{
            NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
            [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        }
        [weakSelf.navigationController popViewControllerAnimated:YES];
        weakSelf.chartModel.isAllowScale = NO;
        
    };
    
    _chartView.selectTopToolBlock = ^(NSInteger index) {
        [weakSelf selectTopTool:index];
    };
    
    _chartView.subTimeBlock = ^{
        [weakSelf subTimeAction];
    };
    
    _chartView.addTimeBlock = ^{
        [weakSelf addTimeAction];
    };

    _chartView.changeTimeBlock = ^{
        [weakSelf changeDate];
    };
    
    [_chartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];

 
    [self.chartView setChartModel:self.chartModel];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf getDataFromNetwork:weakSelf.chartModel];
        
    });
}

#pragma mark Action - Method
- (void)addTimeAction{
    if (self.chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[self.chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (self.chartModel.timeType == TimeType_Day) {
        nextDate = [date dateByAddingDays:1];
    }else if (self.chartModel.timeType == TimeType_Month){
        nextDate = [date dateByAddingMonths:1];
    }else if (self.chartModel.timeType == TimeType_Year){
        nextDate = [date dateByAddingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
    
    [self getDataFromNetwork:self.chartModel];
}

- (void)subTimeAction{
    if (self.chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[self.chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (self.chartModel.timeType == TimeType_Day) {
        nextDate = [date dateBySubtractingDays:1];
    }else if (self.chartModel.timeType == TimeType_Month){
        nextDate = [date dateBySubtractingMonths:1];
    }else if (self.chartModel.timeType == TimeType_Year){
        nextDate = [date dateBySubtractingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];

    [self getDataFromNetwork:self.chartModel];
}

- (void)selectTopTool:(NSInteger)index {
    if (index == -1) {//Params
        DevParamsAlertController *vc = [[DevParamsAlertController alloc] initWithModel:self.chartModel isFull:YES];
        if(@available(iOS 16.0, *)) {
            [self presentViewController:vc animated:NO completion:nil];
        }else{
            [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
        }
        kWeakSelf;
        vc.resultBlock = ^{
            [weakSelf updateParams:weakSelf.chartModel];
        };
        return;
        
    }

    if (index == 0) {//Day
        self.chartModel.timeType = TimeType_Day;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        self.chartModel.params = self.chartModel.dayParams;
        [self getDataFromNetwork:self.chartModel];
        return;

    }
    
    if (index == 1) {//Month
        self.chartModel.timeType = TimeType_Month;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        self.chartModel.allDataArray = @[];
        self.chartModel.params = self.chartModel.monthParams;
        [self.chartView setChartModel:self.chartModel];
        [self getDataFromNetwork:self.chartModel];
        return;
    }
    
    if (index == 2) {//Year
        self.chartModel.timeType = TimeType_Year;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        self.chartModel.allDataArray = @[];
        self.chartModel.params = self.chartModel.yearParams;
        [self.chartView setChartModel:self.chartModel];
        [self getDataFromNetwork:self.chartModel];
        return;
    }
    
    if (index == 4) {//Total
        //self.chartModel.timeType = TimeType_Total;
        return;
    }
}
 
//变更日期
- (void)changeDate{
    DevChartModel *chartModel = self.chartModel;
    //NSString *dateFormatStr = @"yyyy-MM-dd HH:mm";
    WSDateStyle dataStyle = DateStyleShowYearMonthDay;
    if (chartModel.timeType == TimeType_Day) {
        dataStyle = DateStyleShowYearMonthDay;
    }else if (chartModel.timeType == TimeType_Month){
        dataStyle = DateStyleShowYearMonth;
    }else if (chartModel.timeType == TimeType_Year){
        dataStyle = DateStyleShowYear;
    }

    @weakify(self);
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:dataStyle CompleteBlock:^(NSDate *selectDate) {
        @strongify(self);
        //NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];//年-月-日-时-分
        NSUInteger timeSp = [selectDate timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)timeSp];
       
        [self getDataFromNetwork:chartModel];
       
    }];
    datePickerV.dateLabelColor = UIColor.blueColor;//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    if (chartModel.timeType == TimeType_Day) {
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }else if (chartModel.timeType == TimeType_Month){

    }else if (chartModel.timeType == TimeType_Year){
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }
    [datePickerV show];
}
 
- (void)updateParams:(DevChartModel *)chartModel{
    
    if (chartModel.timeType == TimeType_Day) {
        [self getDataFromNetwork:chartModel];
    }

}


#pragma mark - Network
- (void)getDataFromNetwork:(DevChartModel *)chartModel{
    
    NSString *type = @"day";
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[self.chartModel.curTime integerValue]];
    NSInteger currentTime = [date timeIntervalSince1970]*1000;
    
    NSTimeZone *zone  = [NSTimeZone systemTimeZone];
    if(chartModel.timeType == TimeType_Day){
        type = @"day";
    }else if (chartModel.timeType == TimeType_Month){
        type = @"month";
    }else if (chartModel.timeType == TimeType_Year){
        type = @"year";
    }
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"plantId":@(self.plantModel.plant_id),@"currentTime":@(currentTime),@"dateRange":type,@"timeZone":zone.name};
    
    //电站详情
    [BaseModel startWithCompletionAPIKey:H_getRegularStatisticsByPlant argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        chartModel.allDataArray = request.responseJSONObject[@"data"];
        [self.chartView setChartModel:chartModel];
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
        
    
    
}


@end
